package cs2340.flyingkiwi.todoapp;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;

/**
 * This class represents an individual account.
 * 
 * @author Group Flying Kiwi
 * @version 15 Mar 2012
 * 
 * It extends ListActivity class to show the list of categories.
 * Holding down one of the categories will lead to delete or edit category.
 * Pressing menu button will show the add category menu.
 * Clicking one of the categories will lead to the items page which is category class.
 */

public class AccountManager extends ListActivity{
	
	private String accountId;
	
	private static final int ACTIVITY_CREATE=0;
    private static final int ACTIVITY_EDIT=1;
    private static final int ACTIVITY_INSIDE_CATEGORY=2;
	
	private static final int INSERT_ID = Menu.FIRST;
	private static final int DELETE_ID = Menu.FIRST + 1;
	private static final int EDIT_ID = Menu.FIRST + 2;
	
	private ToDoAppDbAdapter mDbHelper;

	/**
	 * onCreate method
	 * @param savedInstanceState
	 */
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.categories);
        
        //Gets the id of the account that was just clicked on and saves that id as accountId
        if (savedInstanceState == null) {
            Bundle extras = getIntent().getExtras();
            if(extras == null) {
                accountId = null;
            } 
            else {
                accountId = extras.getString(ToDoAppDbAdapter.KEY_ACCOUNT_ROWID);
            }
        } 
        else {
            accountId = (String) savedInstanceState.getSerializable(ToDoAppDbAdapter.KEY_ACCOUNT_ROWID);
        }
        
        mDbHelper = new ToDoAppDbAdapter(this);
        mDbHelper.open();
        fillData();
        registerForContextMenu(getListView());

        getListView().setTextFilterEnabled(true);
        
        Button filterButton = (Button) findViewById(R.id.filter);

    	filterButton.setOnClickListener(new View.OnClickListener() {

    		public void onClick(View view) {
    			
    			//Category.this reference to the current Category object that has been instantiated.
    			Intent i = new Intent(AccountManager.this, Filter.class);
    			startActivityForResult(i,0);
    		}

    	});
    }
	
	/**
	 * Fetches data from the database and construct list view for the user.
	 */
	
	private void fillData() {
        // Get all of the rows from the database and create the item list
		Log.d("AManager fillData", "accountId " + accountId);
		Cursor categoriesCursor;
		categoriesCursor = mDbHelper.fetchAllCategories(accountId);
        	startManagingCursor(categoriesCursor);
        
        // Create an array to specify the fields we want to display in the list (only TITLE)
        String[] from = new String[]{ToDoAppDbAdapter.KEY_CATEGORY_TITLE};

        // and an array of the fields we want to bind those fields to (in this case just text1)
        int[] to = new int[]{R.id.category1};

        // Now create a simple cursor adapter and set it to display
        SimpleCursorAdapter categories = 
            new SimpleCursorAdapter(this, R.layout.categories_row, categoriesCursor, from, to);
        setListAdapter(categories);
        Log.d("AccountManager", "Finished the adapter");
    }

	/**
	 * Initialize the contents of the Activity's standard options menu.
	 * @param menu The options menu in which you place your items.
	 * @return return true for the menu to be displayed; if you return false it will not be shown.
	 */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, INSERT_ID, 0, R.string.menu_insert);
        return true;
    }

    /**
     * Default implementation of onMenuItemSelected(int, MenuItem) for activities
     * @param featureId The panel that the menu is in.
     * @param item The menu item that was selected.
     * @return boolean Return true to finish processing of selection, or false to perform the normal menu handling (calling its Runnable or sending a Message to its target Handler).
     */
    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
    	Log.d("Account Manager", "Selected an item");
        switch(item.getItemId()) {
            case INSERT_ID:
                createCategory();
                return true;
        }

        return super.onMenuItemSelected(featureId, item);
    }

    /**
     * Called when a context menu for the view is about to be shown.
     * @param menu The context menu that is being built
     * @param v The view for which the context menu is being built
     * @param menuInfo Extra information about the item for which the context menu should be shown. This information will vary depending on the class of v.
     */
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0, DELETE_ID, 0, R.string.menu_delete);
        menu.add(0, EDIT_ID, 0, R.string.menu_edit);
    }

    /**
     * This hook is called whenever an item in a context menu is selected.
     * @param item The context menu item that was selected.
     * @return boolean Return false to allow normal context menu processing to proceed, true to consume it here.
     */
    @Override
    public boolean onContextItemSelected(MenuItem item) {
    	AdapterContextMenuInfo info;
        switch(item.getItemId()) {
            case DELETE_ID:
                info = (AdapterContextMenuInfo) item.getMenuInfo();
                mDbHelper.deleteCategory(info.id);
                fillData();
                return true;
        
            case EDIT_ID:
            	info = (AdapterContextMenuInfo) item.getMenuInfo();
            	Intent i = new Intent(this, EditCategory.class);
            	Long id2 = new Long(info.id);
            	i.putExtra(ToDoAppDbAdapter.KEY_CATEGORY_ACCOUNTID, accountId);
                i.putExtra(ToDoAppDbAdapter.KEY_CATEGORY_ROWID, id2);
                startActivityForResult(i, ACTIVITY_EDIT);
                fillData();
                return true;
        }
        return super.onContextItemSelected(item);
    }

    /**
     * Starts EditCategory activity to create a new category.
     */
    
    private void createCategory() {
        Intent i = new Intent(this, EditCategory.class);      
        i.putExtra(ToDoAppDbAdapter.KEY_CATEGORY_ACCOUNTID, accountId);
        startActivityForResult(i, ACTIVITY_CREATE);
    }
    
    /**
     * This method will be called when an item in the list is selected.
     * @param l	The ListView where the click happened
     * @param v The view that was clicked within the ListView
     * @param position The position of the view in the list
     * @param id The row id of the item that was clicked
     */
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        Log.d("onListItemClick", "Beginning");
    	super.onListItemClick(l, v, position, id);
    	Long id2 = new Long(id);
    	Log.d("AccountManager", "id "+ id2.toString());
        Intent i = new Intent(this, Category.class);
        i.putExtra(ToDoAppDbAdapter.KEY_CATEGORY_ACCOUNTID, accountId);
        i.putExtra(ToDoAppDbAdapter.KEY_CATEGORY_ROWID, id2.toString());
        startActivityForResult(i, ACTIVITY_INSIDE_CATEGORY);
    }

    /**
     * Called when an activity you launched exits, giving you the requestCode you started it with, 
     * the resultCode it returned, and any additional data from it.
     * @param requestCode The integer request code originally supplied to startActivityForResult(), allowing you to identify who this result came from.
     * @param resultCode The integer result code returned by the child activity through its setResult().
     * @param intent An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        fillData();
    }
}